/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  BaseCommand,
  CommandDialog,
  ObjInfo,
  pickedFaceData,
} from '@amcax/base';
import {
  MultiPickInput,
  PickInputValueType,
} from '@app-cad/common/components/pick-input/3d';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import i18n from 'i18next';
import { wsApi } from '@app-cad/server';
import { CommandFormWrapper } from '@app-cad/common/components/command-form';
import { useState } from 'react';
import { CommandFormFooter } from '@app-cad/common/components/command-form/footer';
function SketchDialog({
  title,
  onClose,
  sketch,
}: {
  title: string;
  onClose: () => void;
  sketch?: ObjInfo;
}) {
  useCommand('sketch-change-plane', { onClose: () => {} });

  const [pickedPlane, setPickedPlane] = useState<pickedFaceData[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  return (
    <CommandDialog
      title={title}
      onClose={onClose}
      placement='topLeft'
    >
      <CommandFormWrapper>
        <MultiPickInput
          placeholder='选择新的支持面'
          value={pickedPlane}
          autoFocus
          onPick={(v) => {
            setPickedPlane(v);
          }}
          allowPickType={[PickInputValueType.Plane]}
          ignoreGlobalPickFilter
        />
        <CommandFormFooter
          onClose={onClose}
          onSubmit={async () => {
            setIsLoading(true);
            try {
              wsApi.editSketchPlane(
                (sketch as any).dxid,
                pickedPlane[0].meshId,
              );

              onClose();
            } finally {
              setIsLoading(false);
            }
          }}
          submitText='完成'
          isSubmitLoading={isLoading}
          isSubmitDisabled={pickedPlane == null}
          isPreviewDisabled={pickedPlane == null}
        />
      </CommandFormWrapper>
    </CommandDialog>
  );
}

export const cmdSketchChangePlane: BaseCommand = {
  id: 'CmdSketchChangePlane',
  label: 'command.sketchChangePlane',
  create: (label, onClose, props) => (
    <SketchDialog
      title={i18n.t(label)}
      onClose={onClose}
      sketch={props}
    />
  ),
};
